<template>
  <div class="home">
    <HomeHeader 
      :category="category"
      @setCurrentCategory="setCurrentCategory"
    />
    <div class="home-container" ref="refreshElm">
      <Suspense>
        <template #default>
          <HomeSwiper />
        </template>
        <template #fallback>
          <div>loading...</div>
        </template>
      </Suspense>
      <HomeList :lessonList="lessonList" />
      <van-loading class="home-loading" type="spinner" v-if="isLoading"/>
      <p class="home-hasmore" v-if="!hasMore">我是有底线的~</p>
    </div>
  </div>
</template>

<script lang="ts">
import HomeHeader from './home-header.vue';
import HomeList from './home-list.vue';
import HomeSwiper from './home-swiper.vue';

import { computed, defineComponent, onMounted, ref } from 'vue';
import { IGlobalState } from '@/store';
import { Store, useStore } from 'vuex';
import { CATEGORY_TYPES } from '@/typings/home';
import * as Types from '@/store/action-types';
import { useLoadMore } from '@/hooks/useLoadMore';

function useCategory(store:Store<IGlobalState>) {
  let category = computed(() => store.state.home.currentCategory);

  function setCurrentCategory(category:CATEGORY_TYPES) {
    store.commit(`home/${Types.SET_CATEGORY}`, category)
  };

  return {
    category,
    setCurrentCategory
  }
};

function useLessonList(store: Store<IGlobalState>) {
  const lessonList = computed(()=> store.state.home.lessons.list);
  onMounted(() => {
    if(lessonList.value.length == 0) {
      store.dispatch(`home/${Types.SET_LESSON_LIST}`);
    }
  });

  return {
    lessonList
  }
}

export default defineComponent({
  name: 'Home',
  components: {
    HomeHeader,
    HomeList,
    HomeSwiper
  },
  setup() {
    let store = useStore<IGlobalState>();
    let { category, setCurrentCategory } = useCategory(store);
    let { lessonList } = useLessonList(store);

    const refreshElm = ref<null | HTMLElement>(null);
    const { isLoading, hasMore } = useLoadMore(refreshElm,store, `home/${Types.SET_LESSON_LIST}`);

    return {
      category,
      setCurrentCategory,
      lessonList,
      refreshElm,
      isLoading,
      hasMore
    }
  }
})
</script>

<style lang="scss">
.home-container {
  position: absolute;
  top: 65px;
  bottom: 50px;
  width: 100%;
  overflow-y: scroll;

  .home-loading {
    width: 30px;
    margin: 20px auto;
  }

  .home-hasmore {
    color: #ccc;
    font-size: 14px;
    line-height: 18px;
    text-align: center;
  }
}
</style>
